/*
 *  cInput.h
 *  Kore-Engine
 *
 *  Description: Holds all the input core
 *
 *  Created by Sean Chapel on 2/1/06.
 *  Copyright 2006 Seoushi Games. All rights reserved.
 *
 */

#include "SDL/SDL.h"
#include "cInput.h"
#include "keys.h"
#include <vector>
#include <map>



cInput::cInput(){}

cInput::~cInput(){}


// Tells if a key is inbetween being pressed and released
bool cInput::IsKeyHeld(eKey Key)
{
	if(m_Keystates[Key] == 'h')
	{
		return true;
	}

	return false;
}


// Tells if a key is pressed
bool cInput::IsKeyDown(eKey Key)
{
	if(m_Keystates[Key] == 'd')
	{
		return true;
	}

	return false;
}

// Tells if a key is released
bool cInput::IsKeyUp(eKey Key)
{
	if(m_Keystates[Key] == 'u')
	{
		return true;
	}

	return false;
}

// Updates keyboard events
/// @returns True is returned on an Exit key being pressed (ctrl+c, window being closed)
bool cInput::Update()
{
	SDL_Event event;
	//this vector holds the keys which have recently changed
	std::vector< eKey > keys;


	while ( SDL_PollEvent( &event ) )
	{
		switch( event.type )
		{
			case SDL_QUIT:
				return true;
				break;
			case SDL_KEYDOWN:
				//save the status in the map (down)
				m_Keystates[event.key.keysym.sym] = 'd';
				//add key to the recent keys changed vector
				keys.push_back((eKey)event.key.keysym.sym);
				break;
			case SDL_KEYUP:
				//save the status in the map (up)
				m_Keystates[event.key.keysym.sym] = 'u';
				//add key to the recent keys changed vector
				keys.push_back((eKey)event.key.keysym.sym);
				break;
			default:
				break;
		}
	}

	//check to see if any keys haven't been released but were press
	// ie being held
	//walks the keystates map, and for each field search its existence in the keys vector.
	//If it exist, it means that the key has recently changed and its status is already processed.
	//If it doesn't exists, it means that the old status is kept, alas, if it was down its new status is held.
	for( std::map<int, char>::iterator itr = m_Keystates.begin(); itr != m_Keystates.end(); itr++)
	{
		//put no status flag
		if( itr->second == 'u' )
		{
			bool keyFound = false;
			for( unsigned int i = 0; i < keys.size(); i++)
			{
				if(keys[i] == itr->first)
				{
					keyFound = true;
					break;
				}
			}

			if( !keyFound )
			{
				itr->second = 'n';
			}
		}
		else if( itr->second == 'd')
		{
			bool keyFound = false;
			for(unsigned int i = 0; i < keys.size(); i++)
			{
				if(keys[i] == itr->first)
				{
					keyFound = true;
					break;
				}
			}

			if( !keyFound )
			{
				itr->second = 'h';
			}
		}
	}

	return false;
}

